import { Component, Fragment } from 'react';
import { createInput } from './decorator';
import { Calendar, List } from 'antd-mobile';

@createInput()
export class CCalendar extends Component {
  state = {
    visible: false,
  };

  handleClick = () => {
    this.setState({
      visible: !this.state.visible,
    });
  };

  close = () => {
    this.setState({
      visible: false,
    });
  };

  onConfirm = (start, end) => {
    this.close();
    if (end) {
      return this.props.onChange([this.format(start), this.format(end)]);
    }
    return this.props.onChange(this.format(v));
  };

  format(value) {
    if (Array.isArray(value)) {
      return value.map(v => v ? this.props.formatter.format(v) : '',
      ).join(' - ');
    }
    return value ? this.props.formatter.format(value) : '';
  }

  getDefaultValue = () => {
    let {value} = this.props
    if (Array.isArray(value)) {
      return value.map(v => typeof v === 'string' ? new Date(v) : v);
    }
    return typeof value === 'string' ? new Date(value) : value
  };

  render() {
    let { name, label, value, onChange, formatter, ...other } = this.props;
    let { visible } = this.state;
    console.log("getDefaultValue" , this.getDefaultValue())
    return (
      <Fragment>

        <List.Item extra={this.format(value)} arrow="horizontal" onClick={this.handleClick}>
          {label}
        </List.Item>
        <Calendar
          onCancel={this.close}
          onConfirm={this.onConfirm}
          defaultValue={this.getDefaultValue()}
          {...other}
          visible={visible}/>
      </Fragment>
    );
  }
}
